<script setup lang="ts">
import { loginAPI } from '@/apis/user';
import type { FormInstance } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useUserStore } from '@/stores/user';
import router from '@/router';
import { REMEMBER_ME_KEY } from '@/constants';
const userStore = useUserStore()
// 数据源
const formData = ref({
  username: '',
  password: '',
  remeberMe: false
})
// 用户名: demo
// 密码:  Hmzs%001


const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 10, message: '账号长度在 3 到 10 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9%]{6,15}$/, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
  ]
}

onMounted(() => {
  const remeberDataStr = localStorage.getItem(REMEMBER_ME_KEY)
  if (remeberDataStr !==null) {
    const userData = JSON.parse(remeberDataStr)
    formData.value = userData
  }
})


// 表单实例
const form = ref<FormInstance>()
const login = async () => {
  // 1. 针对于整个表单进行校验
  // 2. 校验通过, 发请求
  // 3. 请求通过, 存token, 跳转首页
  await form.value!.validate()
  const { username, password } = formData.value
  const res = await loginAPI({ username, password })

  // 判断 记住我的勾选状态 -> true 存用户信息
  if (formData.value.remeberMe) {
    // Cookies.set(REMEMBER_ME_KEY, JSON.stringify(formData.value))
    localStorage.setItem(REMEMBER_ME_KEY, JSON.stringify(formData.value))
  }
  userStore.setToken(res.data.token)
  router.push('/')
}

</script>

<template>
  <div class="login_body">
    <div class="bg" />
    <div class="box">
      <div class="title">智慧园区-登录</div>
      <!-- model 数据源  ref 表单实例对象 rules 校验规则 -->
      <el-form :model="formData" :rules="rules" ref="form">
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="formData.remeberMe">记住我</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login" class="login_btn">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login_body {
  display: flex;
}

.bg {
  width: 60vw;
  height: 100vh;
  background: url("@/assets/login-bg.svg") no-repeat;
  background-position: right top;
  background-size: cover;
}

.box {
  margin: 200px 10% 0;
  flex: 1;

  .title {
    padding-bottom: 76px;
    font-size: 26px;
    font-weight: 500;
    color: #1e2023;
  }

  ::v-deep() {
    .ant-form-item {
      display: flex;
      margin-bottom: 62px;
      flex-direction: column;
    }

    .ant-form-item-label label {
      font-size: 16px;
      color: #8b929d;
    }

    .ant-input,
    .ant-input-password {
      border-radius: 8px;
    }
  }
}

.login_btn {
  width: 100%;
}
</style>
